#include "Server.h"

using boost::asio::ip::udp;


Server::Server(boost::asio::io_service& io_service, std::string *send_msg)
    : socket_(io_service, udp::endpoint(udp::v4(), 6656)){
    msg = send_msg;
    start_receive();

}

Server::Server(boost::asio::io_service& io_service)
    : socket_(io_service, udp::endpoint(udp::v4(), 6656)){
}

Server::~Server(){

}


void Server::start_receive()
  {
    socket_.async_receive_from(boost::asio::buffer(recv_buffer_), remote_endpoint_,
        boost::bind(&Server::handle_receive, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));


  }

void Server::handle_receive(const boost::system::error_code& error,
      std::size_t)
  {
    if (!error || error == boost::asio::error::message_size){
        boost::shared_ptr<std::string> message(new std::string(*msg + "\n"));

        socket_.async_send_to(boost::asio::buffer(*message), remote_endpoint_,
            boost::bind(&Server::handle_send, this, message,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));


        start_receive();

    }

}

void Server::handle_send(boost::shared_ptr<std::string>,
      const boost::system::error_code&,
      std::size_t){

}

void Server::sync_send(std::string *msg){

    try{
        boost::asio::io_service io_service;

        boost::array<char, 1> recv_buf;
        udp::endpoint remote_endpoint;
        boost::system::error_code error;
        socket_.receive_from(boost::asio::buffer(recv_buf),
        remote_endpoint, 0, error);

        if (error && error != boost::asio::error::message_size)
        throw boost::system::system_error(error);

        std::string message = *msg;
        std::cout << *msg << std::endl;

        boost::system::error_code ignored_error;
        socket_.send_to(boost::asio::buffer(message),
          remote_endpoint, 0, ignored_error);

  }

  catch (std::exception& e){
        std::cerr << e.what() << std::endl;
  }


}
